﻿using Microsoft.Phone.Tasks;
using SpaceNeedle.SDK.Windows.Platform.Commands;
using SpaceNeedle.SDK.Windows.Platform.Data;
using SpaceNeedle.SDK.Windows.Platform.Events;
using SpaceNeedle.SDK.WindowsPhone;
using SpaceNeedle.x6473.WindowsPhone.Common;
using SpaceNeedle.x6473.WindowsPhone.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;

namespace SpaceNeedle.x6473.WindowsPhone.ViewModels
{
    public class RequestItemDetailsViewModel : GlobalViewModel
    {
        public event RawEventHandler RequestItemSupportChanged = delegate { };

        public RequestItemDetailsViewModel() : base()
        {
            this.ToggleRequestItemSupportCommand = new RelayCommand(ToggleRequestItemSupport);
        }


        public Uri MapAddress
        {
            get { return this.Get<Uri>(); }
            set { this.Set(value); }
        }

        public string PageTitle
        {
            get { return this.Get<string>(); }
            set { this.Set(value); }
        }

        public Models.Request Request
        {
            get { return this.Get<Models.Request>(); }
            set { this.Set(value); }
        }

        public Models.RequestItem RequestItem
        {
            get { return this.Get<Models.RequestItem>(); }
            set { this.Set(value); }
        }

        public bool IsSupportingRequestItem
        {
            get { return this.Get<bool>(); }
            set { this.Set(value); }
        }

        //public int TotalSupportersCount
        //{
        //    get
        //    {
        //        return AppViewModel.Instance.Properties.SelectedRequestItem.SupportersCount + 1;
        //    }
        //}

        public ICommand ToggleRequestItemSupportCommand { get; set;}
       
        private async void ToggleRequestItemSupport(object param)
        {
            this.IsInProgress = true;

            try
            {
                var supportedRequestItems = await Api.GetRequestItemsSupportedByUser(AppViewModel.Instance.Properties.Me.Id);

                if (supportedRequestItems != null)
                {
                    if (supportedRequestItems.Where(x => x.Id == AppViewModel.Instance.Properties.SelectedRequestItem.Id).Count() == 0)
                    {
                        if (await Api.AddRequestItemSupporter(AppViewModel.Instance.Properties.SelectedRequestItem.Id, AppViewModel.Instance.Properties.Me.Id))
                        {
                            AppViewModel.Instance.Properties.SelectedRequestItem.SupportersCount = await Api.GetRequestItemSupportersCount(AppViewModel.Instance.Properties.SelectedRequestItem.Id);
                        }
                    }
                    else
                    {
                        if (await Api.DeleteRequestItemSupporter(AppViewModel.Instance.Properties.SelectedRequestItem.Id, AppViewModel.Instance.Properties.Me.Id))
                        {
                            AppViewModel.Instance.Properties.SelectedRequestItem.SupportersCount = await Api.GetRequestItemSupportersCount(AppViewModel.Instance.Properties.SelectedRequestItem.Id);
                        }
                    }

                    supportedRequestItems = await Api.GetRequestItemsSupportedByUser(AppViewModel.Instance.Properties.Me.Id);

                    if (supportedRequestItems != null)
                    {
                        this.IsSupportingRequestItem = supportedRequestItems.Where(x => x.Id == AppViewModel.Instance.Properties.SelectedRequestItem.Id).Count() > 0;
                        this.RequestItemSupportChanged();
                    }
                }
                else
                {
                    this.IsSupportingRequestItem = false;
                }
            }
            catch (Exception ex)
            {
                AppServices.Current.DialogService.Show("Não foi possível processar a sua requisição. Por favor tente novamente.");
            }

            this.IsInProgress = false;
    }

        protected async override void Load()
        {
            this.IsInProgress = true;

            await base.LoadAsync();

            if (!string.IsNullOrEmpty(AppViewModel.Instance.Properties.SelectedRequestItemId))
            {
                var requestItems = await AppViewModel.Instance.LoadUserRequests();

                if(requestItems != null)
                {
                    AppViewModel.Instance.Properties.SelectedRequestItem = requestItems.Where(x => x.Id == new Guid(AppViewModel.Instance.Properties.SelectedRequestItemId)).SingleOrDefault();
                }
            }

            this.RequestItem = AppViewModel.Instance.Properties.SelectedRequestItem;
            this.RequestItem.SupportersCount = await Api.GetRequestItemSupportersCount(AppViewModel.Instance.Properties.SelectedRequestItem.Id);

            string number = this.RequestItem.Number.Replace("-", "");

            this.RequestItem.Geoposition = this.RequestItem.Geoposition.Replace(" ","");

            this.MapAddress = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/{0}/12?mapSize=440,160&pushpin={0};68;{1}&mapLayer=mapLayer&format=png&key={2}",
                this.RequestItem.Geoposition,
                this.RequestItem.SupportersCount + 1,
                Properties.BingMapsKey), UriKind.Absolute);
            
            var supportedRequestItems = await Api.GetRequestItemsSupportedByUser(AppViewModel.Instance.Properties.Me.Id);

            if (supportedRequestItems != null)
            {
                this.IsSupportingRequestItem = supportedRequestItems.Where(x => x.Id == AppViewModel.Instance.Properties.SelectedRequestItem.Id).Count() > 0;
            }
            else
            {
                this.IsSupportingRequestItem = false;
            }

            Tracking.SendView(ViewsNames.RequestItemDetails);

            this.IsInProgress = false;

            this.OnLoaded();
        }
    }
}
